package FDSS.UI;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.io.IOException;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.util.Enumeration;

import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTabbedPane;
import javax.swing.UIManager;
import javax.swing.plaf.FontUIResource;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

import com.esri.arcgis.beans.toolbar.ToolbarBean;
import com.esri.arcgis.carto.FeatureLayer;
import com.esri.arcgis.carto.IActiveView;
import com.esri.arcgis.carto.IFeatureIdentifyObj;
import com.esri.arcgis.carto.IFeatureLayer;
import com.esri.arcgis.carto.IFeatureSelection;
import com.esri.arcgis.carto.IIdentify;
import com.esri.arcgis.carto.IIdentifyObj;
import com.esri.arcgis.carto.ILayer;
import com.esri.arcgis.carto.IMap;
import com.esri.arcgis.carto.ISelection;
import com.esri.arcgis.carto.Map;
import com.esri.arcgis.carto.esriSelectionResultEnum;
import com.esri.arcgis.carto.esriViewDrawPhase;
import com.esri.arcgis.controls.ControlsEditingSaveCommand;
import com.esri.arcgis.controls.ControlsMapFullExtentCommand;
import com.esri.arcgis.controls.ControlsMapIdentifyTool;
import com.esri.arcgis.controls.ControlsMapPanTool;
import com.esri.arcgis.controls.ControlsMapZoomInFixedCommand;
import com.esri.arcgis.controls.ControlsMapZoomInTool;
import com.esri.arcgis.controls.ControlsMapZoomOutFixedCommand;
import com.esri.arcgis.controls.ControlsMapZoomOutTool;
import com.esri.arcgis.controls.ControlsMapZoomPanTool;
import com.esri.arcgis.controls.ControlsMapZoomToLastExtentBackCommand;
import com.esri.arcgis.controls.ControlsMapZoomToLastExtentForwardCommand;
import com.esri.arcgis.controls.ControlsOpenDocCommand;
import com.esri.arcgis.controls.ControlsSaveAsDocCommand;
import com.esri.arcgis.controls.ControlsSelectFeaturesTool;
import com.esri.arcgis.controls.IMapControlEvents2Adapter;
import com.esri.arcgis.controls.IMapControlEvents2OnAfterDrawEvent;
import com.esri.arcgis.controls.IMapControlEvents2OnMapReplacedEvent;
import com.esri.arcgis.controls.IMapControlEvents2OnMouseDownEvent;
import com.esri.arcgis.controls.IMapControlEvents2OnMouseMoveEvent;
import com.esri.arcgis.controls.MapControl;
import com.esri.arcgis.controls.TOCControl;
import com.esri.arcgis.datasourcesGDB.SdeWorkspaceFactory;
import com.esri.arcgis.display.DisplayTransformation;
import com.esri.arcgis.display.ITransformEventsAdapter;
import com.esri.arcgis.display.ITransformEventsVisibleBoundsUpdatedEvent;
import com.esri.arcgis.display.RgbColor;
import com.esri.arcgis.display.SimpleFillSymbol;
import com.esri.arcgis.display.SimpleLineSymbol;
import com.esri.arcgis.geodatabase.ICursor;
import com.esri.arcgis.geodatabase.IEnumFeature;
import com.esri.arcgis.geodatabase.IEnumFeatureSetup;
import com.esri.arcgis.geodatabase.IFeature;
import com.esri.arcgis.geodatabase.IFeatureClass;
import com.esri.arcgis.geodatabase.IFeatureCursor;
import com.esri.arcgis.geodatabase.ISelectionSet;
import com.esri.arcgis.geodatabase.ISpatialFilter;
import com.esri.arcgis.geodatabase.IWorkspace;
import com.esri.arcgis.geodatabase.IWorkspaceFactory;
import com.esri.arcgis.geodatabase.SpatialFilter;
import com.esri.arcgis.geodatabase.esriSpatialRelEnum;
import com.esri.arcgis.geometry.Envelope;
import com.esri.arcgis.geometry.IEnvelope;
import com.esri.arcgis.geometry.IGeometry;
import com.esri.arcgis.geometry.IPoint;
import com.esri.arcgis.geometry.IProjectedCoordinateSystem;
import com.esri.arcgis.geometry.ISpatialReference;
import com.esri.arcgis.geometry.ISpatialReferenceFactory;
import com.esri.arcgis.geometry.ITopologicalOperator;
import com.esri.arcgis.geometry.Point;
import com.esri.arcgis.geometry.ProjectedCoordinateSystem;
import com.esri.arcgis.geometry.SpatialReferenceEnvironment;
import com.esri.arcgis.geometry.esriGeometryType;
import com.esri.arcgis.geometry.esriSRGeoCSType;
import com.esri.arcgis.interop.AutomationException;

import com.esri.arcgis.system.AoInitialize;
import com.esri.arcgis.system.EngineInitializer;
import com.esri.arcgis.system.IArray;
import com.esri.arcgis.system.IPropertySet;
import com.esri.arcgis.system.PropertySet;
import com.esri.arcgis.system._WKSPoint;
import com.esri.arcgis.systemUI.esriCommandStyles;
import com.sun.corba.se.spi.activation.Activator;



public class SystemUI extends JFrame {
	//PrescriptionUI prescriptionUI=PrescriptionUI.getInstance();
	private String fileChosen=null;
	private String filepath=null;
	private String filename=null;
	// 状态栏面板
	private JLabel geo = null;
	private JLabel flat = null;
	private JLabel geo_x = null;
	private JLabel geo_y = null;
	private JLabel flat_x = null;
	private JLabel flat_y = null;
	private JLabel place=null;
	
	private JMenuBar menubar = null;
	private JPanel jContentPane = null;
	private JTabbedPane tabPane = null;
	private JTabbedPane tocPane = null;
	private JPanel pane = null;
	private JPanel statusPane = null;
	JMenuItem attribute_q=null;
	JMenuItem location=null;
	JMenuItem solution=null;
	JMenuItem prescription=null;
	
	/*
	 * private JDesktopPane desktopPane=null; private JInternalFrame
	 * tocFrame=null; private JInternalFrame hawkeyeFrame=null;
	 */
	private ToolbarBean toolbarBean = null;
	private TOCControl tocControl = null;
	private static MapControl mapControl = null;
	private MapControl hawkeye = null;

	private SimpleFillSymbol fillSymbol; // 填充符
	private Envelope currentExtent; // 矩形线框
	private Map focusMap; // 焦点图
	// 初始化窗体

	public SystemUI() throws AutomationException, IOException, ClassNotFoundException, SQLException {
		super();
		// 初始化
		initializeArcGISLicenses();
		initialize();
		createOverviewSymbol();
		getExtent();
		addListener();
	}

	// 初始化界面
	private void initialize() throws AutomationException, IOException {
		InitGlobalFont(new Font("楷体", Font.PLAIN, 14));
		
		this.setSize(1366, 763);
		this.setContentPane(getJContentPane());
		this.setTitle("生态种植决策支持系统");
		this.addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowClosing(java.awt.event.WindowEvent e) {
				// System.out.println("windowClosing()");
				try {
					new AoInitialize().shutdown();
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		});
	}

	// 主函数
	public static void main(String[] args) throws AutomationException, IOException, ClassNotFoundException, SQLException {
		EngineInitializer.initializeVisualBeans();
		SystemUI systemUI = new SystemUI();
		systemUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		systemUI.setVisible(true);
	}

	// 初始化主面板
	private JPanel getJContentPane() throws AutomationException, IOException {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			// 防止menuItem被覆盖
			JPopupMenu.setDefaultLightWeightPopupEnabled(false);
			jContentPane.setLayout(null);
			jContentPane.add(getMenu());
			jContentPane.add(getToolbarBean());
			jContentPane.add(getTOCPane());
			jContentPane.add(getHawkeye());
			jContentPane.add(getTabPane());
			jContentPane.add(getStatusPane());
		}
		return jContentPane;
	}

	// 初始化工具栏
	private ToolbarBean getToolbarBean() throws AutomationException, IOException {
		if (toolbarBean == null) {
			toolbarBean = new ToolbarBean();
			toolbarBean.setBounds(0, 22, 1366, 25);
			toolbarBean.addItem(new ControlsOpenDocCommand(), 0, 0, true, 0,
					esriCommandStyles.esriCommandStyleIconOnly);
			toolbarBean.addItem(new ControlsEditingSaveCommand(), 0, 1, true, 0,
					esriCommandStyles.esriCommandStyleIconOnly);
			toolbarBean.addItem(new ControlsSaveAsDocCommand(), 0, 2, true, 0,
					esriCommandStyles.esriCommandStyleIconOnly);
			toolbarBean.addItem(new ControlsMapZoomPanTool(), 0, 3, true, 0,
					esriCommandStyles.esriCommandStyleIconOnly);
			toolbarBean.addItem(new ControlsMapFullExtentCommand(), 0, 4, true, 0,
					esriCommandStyles.esriCommandStyleIconOnly);
			toolbarBean.addItem(new ControlsMapZoomToLastExtentBackCommand(), 0, 5, true, 0,
					esriCommandStyles.esriCommandStyleIconOnly);
			toolbarBean.addItem(new ControlsMapZoomToLastExtentForwardCommand(), 0, 6, true, 0,
					esriCommandStyles.esriCommandStyleIconOnly);
			toolbarBean.addItem(new ControlsMapPanTool(), 0, 7, true, 0, esriCommandStyles.esriCommandStyleIconOnly);
			toolbarBean.addItem(new ControlsMapZoomInTool(), 0, 8, true, 0, esriCommandStyles.esriCommandStyleIconOnly);
			toolbarBean.addItem(new ControlsMapZoomOutTool(), 0, 9, true, 0,
					esriCommandStyles.esriCommandStyleIconOnly);
			toolbarBean.addItem(new ControlsMapZoomInFixedCommand(), 0, 10, true, 0,
					esriCommandStyles.esriCommandStyleIconOnly);
			toolbarBean.addItem(new ControlsMapZoomOutFixedCommand(), 0, 11, true, 0,
					esriCommandStyles.esriCommandStyleIconOnly);
			toolbarBean.addItem(new ControlsMapIdentifyTool(), 0, 12, true, 0,
					esriCommandStyles.esriCommandStyleIconOnly);
			toolbarBean.addItem(new ControlsSelectFeaturesTool(), 0, 13, true, 0, esriCommandStyles.esriCommandStyleIconOnly);
			toolbarBean.setBuddyControl(getMapControl());

		}
		return toolbarBean;
	}

	// 初始化菜单栏
	private JMenuBar getMenu() {
		if (menubar == null) {
			menubar = new JMenuBar();
			menubar.setBounds(0, 0, 1366, 22);
			//文件
			JMenu filem = new JMenu("文件(F)");
			menubar.add(filem);
			JMenuItem open_item = new JMenuItem("打开(O)");
			filem.add(open_item);
			filem.addSeparator();
			//查询
			JMenu querym = new JMenu("查询(Q)");
			menubar.add(querym);
				//属性查询
			attribute_q=new JMenuItem("属性查询");
			querym.add(attribute_q);
			querym.addSeparator();
				//图查属性 ？？？
			location=new JMenuItem("定位");
			querym.add(location);
			//专题图
			JMenu themmapm = new JMenu("专题图(S)");
			menubar.add(themmapm);

			JMenu analysism = new JMenu("空间分析(A)");
			menubar.add(analysism);

			JMenu decision = new JMenu("施肥决策(P)");
			menubar.add(decision);
				//决策
			solution=new JMenuItem("施肥决策");
			decision.add(solution);
			
			prescription=new JMenuItem("施肥处方");
			decision.add(prescription);
			
			JMenu helpm = new JMenu("帮助(H)");
			menubar.add(helpm);
			
			
			
		}
		return menubar;
	}

	// 初始化TOCControl
	private TOCControl getTOCControl() throws AutomationException, IOException {
		if (tocControl == null) {
			tocControl = new TOCControl();
			tocControl.setBounds(1, 48, 250, 460);
			tocControl.setBuddyControl(getMapControl());
		}
		return tocControl;
	}

	private MapControl getHawkeye() throws AutomationException, IOException {
		if (hawkeye == null) {
			hawkeye = new MapControl();
			hawkeye.setBounds(1, 509, 250, 170);
		}
		return hawkeye;
	}

	private JTabbedPane getTOCPane() throws AutomationException, IOException {
		if (tocPane == null) {
			tocPane = new JTabbedPane();
			tocPane.setBounds(1, 48, 250, 460);
			tocPane.add(getTOCControl(), "内容表");
		}
		return tocPane;
	}

	private JTabbedPane getTabPane() {
		if (tabPane == null) {
			tabPane = new JTabbedPane();
			tabPane.setBounds(251, 48, 1115, 631);
			tabPane.add(getMapControl(), "地图");
			tabPane.add(getMyLayout(), "布局");
		}
		return tabPane;
	}

	// 初始化MapControl
	static MapControl getMapControl() {
		if (mapControl == null) {
			mapControl = new MapControl();
		}
		return mapControl;
	}

	private JPanel getMyLayout() {
		if (pane == null) {
			pane = new JPanel();
			pane.setBounds(251, 48, 1115, 631);
		}
		return pane;
	}

	/*
	 * private JDesktopPane getDesktopPane(){ if(desktopPane==null){
	 * desktopPane=new JDesktopPane(); desktopPane.setBounds(0, 48, 1366, 692);
	 * desktopPane.add(getTOCJInternalFrame());
	 * desktopPane.add(getHawJInternalFrame()); } return desktopPane; } private
	 * JInternalFrame getTOCJInternalFrame(){ if(tocFrame==null){ tocFrame=new
	 * JInternalFrame(); tocFrame.setBounds(0, 0, 250, 480);
	 * tocFrame.setTitle("內容表"); tocFrame.add(getTOCControl());
	 * tocFrame.setMaximizable(true); tocFrame.setClosable(true);
	 * tocFrame.setVisible(true); } return tocFrame; } private JInternalFrame
	 * getHawJInternalFrame(){ if(hawkeyeFrame==null){ hawkeyeFrame=new
	 * JInternalFrame(); hawkeyeFrame.setBounds(0, 473, 250, 181);
	 * hawkeyeFrame.setTitle("內容表"); hawkeyeFrame.add(getTOCControl());
	 * hawkeyeFrame.setMaximizable(true); hawkeyeFrame.setClosable(true);
	 * hawkeyeFrame.setVisible(true); } return hawkeyeFrame; }
	 */
	// 状态栏面板
	private JPanel getStatusPane() {
		if (statusPane == null) {
			statusPane = new JPanel();
			statusPane.setLayout(null);
			geo = new JLabel("地理坐标  ");
			geo.setBounds(220, 2, 75, 23);
			geo_x = new JLabel();
			geo_x.setBounds(288, 2, 150, 23);
			geo_y = new JLabel();
			geo_y.setBounds(450, 2, 150, 23);
			flat = new JLabel("平面坐标  ");
			flat.setBounds(630, 2, 75, 23);
			flat_x = new JLabel();
			flat_x.setBounds(705, 2, 150, 23);
			flat_y = new JLabel();
			flat_y.setBounds(865, 2, 150, 23);
			place=new JLabel();
			place.setBounds(1115, 2, 150, 23);
			statusPane.setBounds(0, 680, 1366, 23);

			statusPane.add(geo);
			statusPane.add(geo_x);
			statusPane.add(geo_y);
			statusPane.add(flat);
			statusPane.add(flat_x);
			statusPane.add(flat_y);
			statusPane.add(place);
		}
		return statusPane;
	}

	// 点击事件
	private void addListener() throws IOException {
		/*
		 * 1、打开地图，鹰眼也打开 2、鼠标移动，获取坐标
		 */
		mapControl.addIMapControlEvents2Listener(new IMapControlEvents2Adapter() {
			private static final long serialVersionUID = 1L;

			public void onMapReplaced(IMapControlEvents2OnMapReplacedEvent event)
					throws AutomationException, IOException {
				hawkeye.loadMxFile(mapControl.getDocumentFilename(), null, null);
				getExtent();
			}
			
			
			public void onMouseDown(IMapControlEvents2OnMouseDownEvent event) throws AutomationException, IOException{
				if(!mapIsEmpty()){
					if(event.getButton()==1){
						
						PrescriptionUI prescriptionUI=new PrescriptionUI();
						prescriptionUI.setLocation(event.getX(), event.getY());
						prescriptionUI.getCoordinateXText().setText(""+event.getMapX());
						prescriptionUI.getCoordinateYText().setText(""+event.getMapY());
						if(!mapIsEmpty()){
							prescriptionUI.getLocationText().setText(getLocation(event.getMapX(),event.getMapY()));
						}else{
							prescriptionUI.getLocationText().setText("");
						}
				}
				}
				
				
				/*IMap map;
				IPoint pPoint;
				map = mapControl.getMap();
				pPoint = mapControl.toMapPoint(event.getX(), event.getY());
				IIdentify pIdentify;
				pIdentify = (IIdentify)map.getLayer(0);
				IArray pIDArray;
				IFeatureIdentifyObj pFeatIdObj;
				IIdentifyObj pIdObj;

				//点选
				IEnvelope pEnv=new Envelope();
				pEnv =mapControl.getActiveView().getExtent();
				pEnv.setHeight(100);
				pEnv.setWidth(100);
				pEnv.centerAt(pPoint);
				pIDArray = pIdentify.identify(pEnv);

				//矩形选择
				 //IEnvelope testIRectangleElement;
				//testIRectangleElement = axMapControl1.TrackRectangle();
				//pIDArray = pIdentify.Identify(testIRectangleElement);
				//i = pIDArray.Count;
				if (pIDArray != null)
				{
				    for (int i = 0; i <= pIDArray.getCount(); i++)
				    {
				        pFeatIdObj = (IFeatureIdentifyObj)pIDArray.getElement(i);
				        pIdObj = (IIdentifyObj)pFeatIdObj;
				        //pIdObj.flash(mapControl.getActiveView().getScreenDisplay());
				        //消息显示查询目标的信息
				        System.out.println("Layer:" + pIdObj.getLayer().getName() + "Feature:" + pIdObj.getName());
				    }
				}
				else
				{
					System.out.println("No feature identified.");
				}*/

				
			}
			// 获取坐标位置信息
			public void onMouseMove(IMapControlEvents2OnMouseMoveEvent event) throws AutomationException, IOException {
				//prescriptionUI.dispose();
				double geoX, geoY;
				if(!mapIsEmpty()){
					place.setText(getLocation(event.getMapX(),event.getMapY()));
					IMap pMap = mapControl.getActiveView().getFocusMap();
					ISpatialReferenceFactory pfactory = new SpatialReferenceEnvironment();
					ISpatialReference flatref = pMap.getSpatialReference();

					ISpatialReference earthref = pfactory.createGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_Beijing1954);
					_WKSPoint wkspoint=new _WKSPoint();
					wkspoint.x=event.getMapX();
					wkspoint.y=event.getMapY();
					IPoint point=new Point();
					point.putCoords(event.getMapX(), event.getMapY());
					
					IGeometry geo=(IGeometry)point;
					geo.setSpatialReferenceByRef(flatref);
					geo.project(earthref);
					geoX=point.getX();
					geoY=point.getY();
					
					geo_x.setText(" X :" +geoX+"E");
					//System.out.println(Double.parseDouble(mapX));
					geo_y.setText(" Y :" +geoY+"N");
					flat_x.setText(" X :" + wkspoint.x);
					flat_y.setText(" Y :" + wkspoint.y);

				}else{
					place.setText("");
					//System.out.println("null");
				}
				
								
				
				/*IFeatureLayer featureLayer=new FeatureLayer();
				featureLayer=null;
				for(int i=0;i<mapControl.getMap().getLayerCount();i++){
					ILayer layer=mapControl.getMap().getLayer(i);
					//System.out.println(layer.getName());
					if(layer.getName()=="中国地州界"){
						featureLayer=(IFeatureLayer)layer;
						System.out.println(layer.getName());
						break;
					}
				}
				
				ISpatialFilter spatialFilter=new SpatialFilter();
				spatialFilter.setGeometryByRef(point);
				switch(featureLayer.getFeatureClass().getShapeType()){
				case esriGeometryType.esriGeometryPoint:
					spatialFilter.setSpatialRel(esriSpatialRelEnum.esriSpatialRelContains);
					break;
				case esriGeometryType.esriGeometryPolyline:
					spatialFilter.setSpatialRel(esriSpatialRelEnum.esriSpatialRelCrosses);
					break;
				case esriGeometryType.esriGeometryPolygon:
					spatialFilter.setSpatialRel(esriSpatialRelEnum.esriSpatialRelEnvelopeIntersects);
					break;
				default:
					System.out.println("null");
					break;
				}
				IFeatureCursor cursor=featureLayer.getFeatureClass().search(spatialFilter, false);
				IFeature feature=cursor.nextFeature();
				while(feature!=null){
					String print=(String)feature.getValue(feature.getFields().findField(""));
					System.out.print(print);
					feature=cursor.nextFeature();
				}*/
				
			}
		});

		hawkeye.addIMapControlEvents2Listener(new IMapControlEvents2Adapter() {
			private static final long serialVersionUID = 1L;

			public void onAfterDraw(IMapControlEvents2OnAfterDrawEvent evt) throws IOException {
				if (evt.getViewDrawPhase() == esriViewDrawPhase.esriViewForeground) {
					// 在MapBean上绘制形状。
					hawkeye.drawShape(currentExtent, fillSymbol);
				}
			}

			public void onMouseDown(IMapControlEvents2OnMouseDownEvent evt)
					throws AutomationException, UnknownHostException, IOException {
				if (hawkeye.getMap() != null) {
					if (evt.getButton() == 1) {
						Envelope pEnvelope = new Envelope();
						IPoint point = new Point();
						// 获取点的位置
						point.putCoords(evt.getMapX(), evt.getMapY());
						// 视图发生变换，捕获区域
						pEnvelope = (Envelope) focusMap.getExtent();
						// 将这个矩形的边框移动到参数pPoint的位置
						pEnvelope.centerAt(point);
						mapControl.setExtent(pEnvelope);

					} else if (evt.getButton() == 2) {
						// 绘制矩形框
						IEnvelope pEnvelope = hawkeye.trackRectangle();
						mapControl.setExtent(pEnvelope);
					}
				}
			}
		});
		
		//**点击事件**///
		//属性查询点击事件
		attribute_q.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				try {
					if(!mapIsEmpty()){
						QueryUI queryUI=new QueryUI();
						queryUI.setVisible(true);
						queryUI.setAlwaysOnTop(true);
					}
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
			}
		});
		location.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				try {
					if(!mapIsEmpty()){
						LocationUI location=new LocationUI();
						location.setVisible(true);
						location.setAlwaysOnTop(true);
					}
				} catch (SecurityException | IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		solution.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				try {
					if(!mapIsEmpty()){
						DecisionUI decisionUI=new DecisionUI();
						decisionUI.setVisible(true);
						decisionUI.setAlwaysOnTop(true);
					}
				} catch (SecurityException | IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
	}
	//画线框
	private void createOverviewSymbol() throws IOException {
		RgbColor color = new RgbColor();
		color.setRed(255);
		color.setGreen(0);
		color.setBlue(0);
		color.setTransparency((byte) 120);
		SimpleLineSymbol outline = new SimpleLineSymbol();
		outline.setWidth(1);
		outline.setColor(color);
		fillSymbol = new SimpleFillSymbol();
		color.setTransparency((byte) 0);
		fillSymbol.setColor(color);
		fillSymbol.setOutline(outline);
	}
	//取得当前视图
	private void getExtent() throws AutomationException, IOException {
		if (mapControl.getDocumentFilename() != null) {
			// 设置地图范围
			hawkeye.setExtent(hawkeye.getFullExtent()); // getFullExtent()获得包含图层的所有要素
			
			// 得到焦点图
			focusMap = (Map) mapControl.getActiveView().getFocusMap();
			currentExtent = (Envelope) focusMap.getExtent(); // 获取到焦点图的当前范围
			// 管理地图到设备转换
			DisplayTransformation dt = (DisplayTransformation) focusMap.getScreenDisplay().getDisplayTransformation();
			dt.addITransformEventsListener(new ITransformEventsAdapter() {
				private static final long serialVersionUID = 1L;
				// 当可见边界更新时的时间
				public void visibleBoundsUpdated(ITransformEventsVisibleBoundsUpdatedEvent evt) throws IOException {
					// System.out.println("update");
					// 将currentExtent设置为新的可见范围。
					currentExtent = (Envelope) evt.getSender().getVisibleBounds();
					// 刷新地图组件前景阶段。
					hawkeye.refresh(esriViewDrawPhase.esriViewForeground, null, null);
				}
			});
		}

	}
	
	private static void InitGlobalFont(Font font) {
		FontUIResource fontRes = new FontUIResource(font);
		for (Enumeration<Object> keys = UIManager.getDefaults().keys();
		keys.hasMoreElements(); ) {
		Object key = keys.nextElement();
		Object value = UIManager.get(key);
		if (value instanceof FontUIResource) {
			UIManager.put(key, fontRes);
		}
		}
	}
	
	public String getLocation(double x,double y) throws AutomationException, IOException{
		IIdentify pIdentify;    //IIdentify接口（要素图层下的一个接口）定义了获得要素图层单个要素的属性的捷径方法。它有一Identify方法，返回一个IArray数组对象。
        IPoint pPoint;
        IArray pIDArray;
        IFeatureIdentifyObj pFeatIdObj;//定义一个要素对象
        IIdentifyObj pIdObj;
        IMap pMap = mapControl.getMap();//将当前地图赋给地图对象pMap
        pIdentify = (IIdentify) pMap.getLayer(3);//将图层赋给图层对象pIdentify
        //System.out.println(mapControl.getLayer(0).getName());
        pPoint = new Point();//定义了一个实现IPoint接口的点对象
        pPoint.putCoords(x, y);//pPoint.PutCoords用来设置点的X,Y值从而创建一个点对象。       
        pPoint.setSpatialReferenceByRef(pMap.getSpatialReference());
        pIDArray = pIdentify.identify(pPoint);//Identify方法返回一个Array数组对象
        if (pIDArray != null)
        {
            pFeatIdObj = (IFeatureIdentifyObj)pIDArray.getElement(0);//获得要素集数组中的第一个元素
            pIdObj = (IIdentifyObj) pFeatIdObj;
           // pIdObj.flash(mapControl.getActiveView().getScreenDisplay());//选中要素闪烁
           //System.out.println("Feature" + pIdObj.getName());//显示要素所在图层的名字，要素的的名字
           return pIdObj.getName();
        }else{
        	return null;
        }
	}
	
	public boolean mapIsEmpty() throws AutomationException, IOException{
		if(!(mapControl.getDocumentFilename().equals(""))){
			return false;
		} else{
			return true;
		}
	}
	
	/*private double ConvertPixelsToMapUnits(IActiveView pActiveView, double pixelUnits)  
	{  
	    // Uses the ratio of the size of the map in pixels to map units to do the conversion  
	    IPoint p1 = pActiveView.getScreenDisplay().getDisplayTransformation().getVisibleBounds().getLowerLeft();  
	    IPoint p2 = pActiveView.getScreenDisplay().getDisplayTransformation().getVisibleBounds().getLowerRight();  
	    int x1, x2, y1, y2;  
	    pActiveView.getScreenDisplay().getDisplayTransformation().fromMapPoint(p1, x1, y1);  
	    pActiveView.ScreenDisplay.DisplayTransformation.FromMapPoint(p2, x2, y2);  
	    double pixelExtent = x2 - x1;  
	    double realWorldDisplayExtent = pActiveView.ScreenDisplay.DisplayTransformation.VisibleBounds.Width;  
	    double sizeOfOnePixel = realWorldDisplayExtent / pixelExtent;  
	    return pixelUnits * sizeOfOnePixel;  
	}  */
	     
	
	//连接数据库
	private IWorkspace getWorkspace() throws UnknownHostException, IOException{
		IWorkspace workspace =null;
		IPropertySet propertySet = new PropertySet();
		propertySet.setProperties("SERVER", "server");  
		propertySet.setProperties("INSTANCE", "5151");
		propertySet.setProperties("DATABASE", "sde");
		propertySet.setProperties("USER", "sa");
		propertySet.setProperties("PASSWORD", "momin");
		propertySet.setProperties("VERSION", "SDE.DEFAULT");
		IWorkspaceFactory workspaceFactory = new SdeWorkspaceFactory();
		workspace=workspaceFactory.open(propertySet, 0);
		System.out.println("连接成功！");
		return workspace;
	}
	
	
	// 初始化许可证
	static void initializeArcGISLicenses() {
		try {
			com.esri.arcgis.system.AoInitialize ao = new com.esri.arcgis.system.AoInitialize();
			if (ao.isProductCodeAvailable(
					com.esri.arcgis.system.esriLicenseProductCode.esriLicenseProductCodeEngine) == com.esri.arcgis.system.esriLicenseStatus.esriLicenseAvailable)
				ao.initialize(com.esri.arcgis.system.esriLicenseProductCode.esriLicenseProductCodeEngine);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
